package com.xtwy.server;

import com.xtwy.config.ServerConfig;
import com.xtwy.listener.RXIpStatListener;
import com.xtwy.handler.RXWsMsgHandler;
import com.xtwy.listener.ServerAioListener;
import org.tio.server.ServerGroupContext;
import org.tio.websocket.server.WsServerStarter;

/**
 * @描述：
 * 消息服务
 *
 * @公司：  山西迅腾伟业
 * @版本：  1.0.0
 * @日期：  18/08/08
 * @作者：  侯建军
 */
public class MessageServerStart {
    //服务启
    private WsServerStarter wsServerStarter;
    private ServerGroupContext serverGroupContext;
    public MessageServerStart(){}

    /**
     * 有参构造
     * @param port 端口号
     * @param wsMsgHandler 消息处理器
     * @throws Exception
     */
    public MessageServerStart(int port, RXWsMsgHandler wsMsgHandler) throws Exception {
        wsServerStarter = new WsServerStarter(port, wsMsgHandler);

        serverGroupContext = wsServerStarter.getServerGroupContext();
        //添加配置
        serverGroupContext.setName(ServerConfig.PROTOCOL_NAME);
        //添加监听
        serverGroupContext.setServerAioListener(ServerAioListener.me);

        //设置ip监控
        serverGroupContext.setIpStatListener(RXIpStatListener.me);
        //设置ip统计时间段
        serverGroupContext.ipStats.addDurations(ServerConfig.IpStatDuration.IPSTAT_DURATIONS);

        //设置心跳超时时间
        serverGroupContext.setHeartbeatTimeout(ServerConfig.HEARTBEAT_TIMEOUT);
        //如果你希望通过wss来访问，就加上下面的代码吧，不过首先你得有SSL证书（证书必须和域名相匹配，否则可能访问不了ssl）
//		String keyStoreFile = "classpath:config/ssl/keystore.jks";
//		String trustStoreFile = "classpath:config/ssl/keystore.jks";
//		String keyStorePwd = "214323428310224";
//		serverGroupContext.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
    }

    /**
     *  开始服务
     * @throws Exception
     */
    public static void start() throws Exception {
        MessageServerStart appStarter = new MessageServerStart(ServerConfig.SERVER_PORT, RXWsMsgHandler.me);
        appStarter.wsServerStarter.start();
    }

    /**
     * 服务组上下文
     * @return
     */
    public ServerGroupContext getServerGroupContext() {
        return serverGroupContext;
    }

    public WsServerStarter getWsServerStarter() {
        return wsServerStarter;
    }

    /**
     * 服务启动
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        start();
    }
}
